package dao.implDao;

import model.User;
import org.hibernate.Criteria;
import org.hibernate.Session;
import util.HibernateUtil;

import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;

/**
 * Created with IDEA.
 * User: Ѱ
 * Date: 20.07.14
 * Time: 10:28
 */
public class UserDao {


    public List<User> getAllUsers() throws SQLException {
        List<User> list = null;
        Session session = null;
        try {
            session = HibernateUtil.getSessionFactory().getCurrentSession();
            session.beginTransaction();
            Criteria query = session.createCriteria(User.class);
            list = query.list();
            session.getTransaction().commit();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    public void addUser(User user) throws SQLException {
        Session session = null;
        try {
            session = HibernateUtil.getSessionFactory().getCurrentSession();
            session.beginTransaction();
            session.save(user);
            session.getTransaction().commit();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void updateUser(User user) throws SQLException {
        Session session = null;
        try {
            session = HibernateUtil.getSessionFactory().getCurrentSession();
            session.beginTransaction();
            session.update(user);
            session.getTransaction().commit();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public User getById(Long id) throws SQLException {
        try {
            Iterator<User> userIterator = getAllUsers().iterator();
            User tmp;
            while (userIterator.hasNext()) {
                tmp = userIterator.next();
                if (tmp.getId() == id) {
                    return tmp;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public void deleteUser(User user) throws SQLException {
        Session session = null;
        try {
            session = HibernateUtil.getSessionFactory().getCurrentSession();
            session.beginTransaction();
            session.delete(user);
            session.getTransaction().commit();
        } catch (Exception e) {
            e.printStackTrace();
        }
        }



}
